//
//  SheJiViewController.m
//  LiangPinZS
//
//  Created by hwd on 17/3/10.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "ForumFaBu.h"
#import "TZImagePickerController.h"
#import "ImageVCell.h"
#import "SelfTextView.h"

@interface ForumFaBu ()<UITextViewDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate,UICollectionViewDelegate,UICollectionViewDataSource,TZImagePickerControllerDelegate>
@property (nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,strong)SelfTextView *textInputV;

@property (nonatomic, retain) NSMutableArray *photos;
@property (nonatomic, copy) NSString *content;
@property (nonatomic, retain) NSMutableArray *photoUrls;
@end

@implementation ForumFaBu

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self creatView];
}

-(void)creatView
{
    _photos = [NSMutableArray new];
    _photoUrls = [NSMutableArray new];
    [self initTitleWithTitle:@"发帖"];
    [self initLeftBarButtonWithImage:@"back"];
    [self initRightBarButtonWithTitle:@"发送" andTitleColor:[UIColor whiteColor] andFont:16*screenW_6];
    [self.view addSubview:self.collectionView];
}

//构建视图
-(UICollectionView *)collectionView
{
    if (!_collectionView)
    {
        //布局约束
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
        layout.minimumInteritemSpacing = 5*screenW_6 ;
        layout.minimumLineSpacing = 5*screenW_6 ;
        layout.scrollDirection =  UICollectionViewScrollDirectionVertical ;
        layout.sectionInset =  UIEdgeInsetsMake(5*screenW_6,15*screenW_6,5*screenW_6,15*screenW_6);
        layout.itemSize =  CGSizeMake((SCREENW-40*screenW_6)/3.0,(SCREENW-40*screenW_6)/3.0);
        
        //_collectionView
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,0,SCREENW, SCREENH-64) collectionViewLayout:layout];
        _collectionView.delegate = self ;
        _collectionView.dataSource = self ;
        _collectionView.scrollEnabled = YES;
        _collectionView.backgroundColor =[UIColor whiteColor];
        [_collectionView registerClass:[ImageVCell class] forCellWithReuseIdentifier:@"Cell"];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeader"];
    }
    return _collectionView;
}
#pragma mark-CollectionView专区
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _photos.count + 1;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
        return CGSizeMake(0,180*screenW_6);
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ImageVCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    if (indexPath.row == _photos.count) {
        [cell loadCell:nil isShow:NO];//加载添加图片的
    }else{
        [cell loadCell:_photos[indexPath.row] isShow:YES];//展示图片
    }
    __weak typeof(self) weakSlef = self;
    cell.block = ^(){
        [weakSlef.photos removeObjectAtIndex:indexPath.row];
        [collectionView reloadData];
    };
    return cell;
}

//对头视图或者尾视图进行设置
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSlef = self;
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
       UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"UICollectionViewHeader" forIndexPath:indexPath];
        SelfTextView *textInputV =[[SelfTextView alloc]initWithFrame:CGRectMake(15*screenW_6,15*screenW_6,SCREENW-30*screenW_6,150*screenW_6) text:_content PlaceHodel:@"请输入详细的文字内容～"];
        textInputV.backgroundColor = backColor;
        [view addSubview:textInputV];
        textInputV.blcok =  ^(NSString *text){
            weakSlef.content = text;
        };
        return view;
    }
    return nil;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == _photos.count) {
        if (_photos.count == 3) {
            [TomamaUI creatAlertWithTarget:self message:@"最多上传3张图片" timeInterval:2];
            return;
        }
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:3-_photos.count delegate:nil];
        imagePickerVc.allowPickingVideo = NO;
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets,BOOL isSelectOriginalPhoto) {
            [_photos addObjectsFromArray:photos];
            [collectionView reloadData];
        }];
        [[TomamaUI getTopVC] presentViewController:imagePickerVc animated:YES completion:nil];
    }else{
//        [_photos removeObjectAtIndex:indexPath.row];
//        [collectionView reloadData];
    }
}

-(void)onTapRightBarButton
{
    if (!_content.length) {
        [TomamaUI creatAlertWithTarget:self message:@"请输入文字" timeInterval:2];
        return;
    }
    [HudHelper showProgressHudWithMessage:@"" toView:self.view];
    [self upImage];
}

-(void)upImage
{
    if (_photos.count == 0) {
        [self upPost];
        return;
    }
    HWDUpALIPhoto *ALIPhoto = [[HWDUpALIPhoto alloc]initWithImages:_photos success:^(NSArray *imageNames) {
        [_photoUrls addObjectsFromArray:imageNames];
        [self upPost];
    } fail:^{//上传失败
        [HudHelper hideHudToView:self.view];
        [HudHelper showHudWithMessage:@"上传失败，请重试" toView:self.view];
    }];
}

-(void)upPost
{
    NSString *imgList = @"";
    for (int i = 0; i < _photoUrls.count; i++) {
        if (i == 0) {
            imgList = _photoUrls[i];
        }else{
            imgList = [NSString stringWithFormat:@"%@,%@",imgList,_photoUrls[i]];
        }
    }
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [HttpRequest PostrequestUrl:@"/post/addPost" Dic:@{@"user.id":[Storage getToken],@"imgList":imgList,@"content":_content} completion:^(NSDictionary *responseDic) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [HudHelper hideHudToView:self.view];
                if ([responseDic[@"success"] boolValue])  {
                    [TomamaUI creatAlertWithTarget:self message:@"发布成功" timeInterval:2 block:^{
                        [self.navigationController popViewControllerAnimated:YES];
                    }];
                }else{
                    [TomamaUI creatAlertWithTarget:self message:responseDic[@"msg"] timeInterval:2];
                }
            });
        }];
    });
}

@end
